package com.njit.WeStudy.control;

import com.njit.WeStudy.dataobject.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @author yuruiqiao
 * @date  2020-01-22
 * @description  实现本地文件的上传
 * */
@RestController
public class FileUploadController {

    // 执行上传
    @RequestMapping(path = "/upload")
    public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file,HttpSession session) {
        int userId;
        try{
            userId = ((User)session.getAttribute("user")).getUserId();
        }catch (NullPointerException e){
            return "false";
        }
        //文件的文件名加扩展名
        String originalFilename = file.getOriginalFilename();
        //获取文件名的后缀
        String fileType = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf(".")).substring(1);
        //上传的真实路径,以userId为分割
        String filePath =request.getServletContext().getRealPath("upload/"+userId+"/"+fileType);
        // 获取上传文件名,并生成新的,唯一的文件名
        String filename = UUID.randomUUID()+"."+fileType;
        // 新建文件
        File filepath = new File(filePath, filename);
        // 判断路径是否存在，如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            boolean isSuccess = filepath.getParentFile().mkdirs();
            if (!isSuccess) {
                System.out.println("mkdirs-error");
            }
        }
        try {
            // 写入文件,File.separator为了使文件路径更加合理化,跨平台
            file.transferTo(new File(filePath + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/upload/"+userId+"/"+fileType+"/" +filename;
    }
}
